﻿using InventorySystem.Configs;
using InventorySystem;
using PlayerRoles.PlayableScps.Scp3114;
using PlayerRoles.RoleAssign;
using PlayerRoles;
using RgCore.GameData;
using RgCore.GameModes;
using RgCore.RoleAssignment;
using System;
using System.Collections.Generic;
using System.Linq;
using static RgCore.RoleAssignment.RoleAssignment;
using Exiled.API.Features;
using HarmonyLib;

namespace RgCore.Patches
{
    [HarmonyPatch(typeof(RoleAssigner), nameof(RoleAssigner.OnRoundStarted))]
    public static class OnRoundStartedPatch
    {
        [HarmonyPrefix]
        public static bool Prefix()
        {
            try
            {
                Log.Info("预开始回合");
                RgCore.Starting();
                StartPlayer.Clear();
                foreach (var item in RgCore.instance.Config.RoleDefaultItems)
                {
                    if (StartingInventories.DefinedInventories.ContainsKey(item.Key))
                    {
                        InventoryRoleInfo iri = StartingInventories.DefinedInventories[item.Key];
                        InventoryRoleInfo newiri = new InventoryRoleInfo(item.Value.ToArray(), iri.Ammo);
                        StartingInventories.DefinedInventories[item.Key] = newiri;
                    }
                }
                foreach (var item in RgCore.instance.Config.RoleDefaultAmmo)
                {
                    if (StartingInventories.DefinedInventories.ContainsKey(item.Key))
                    {
                        InventoryRoleInfo iri = StartingInventories.DefinedInventories[item.Key];
                        InventoryRoleInfo newiri = new InventoryRoleInfo(iri.Items, item.Value);
                        StartingInventories.DefinedInventories[item.Key] = newiri;
                    }
                }
                string SpawnQueue = (RgCore.instance.Config.GameModeEnabled && !RgCore.instance.Config.SafeMode) ? GameMode.CurrentGameMode.GetSpawnQueue() : GameCore.ConfigFile.ServerConfig.GetString("team_respawn_queue", "4014314031441404134041434414");
                Log.Info("生成队列：" + SpawnQueue);
                int playerstospawn = Server.PlayerCount - Player.List.Count(x => x.IsOverwatchEnabled);
                List<SpawnTeam> queue = new List<SpawnTeam>();
                for (int i = 0; i < SpawnQueue.Length && i < playerstospawn; i++)
                {
                    SpawnTeam team = (SpawnTeam)(SpawnQueue[i] - '0');
                    if (Enum.IsDefined(typeof(SpawnTeam), team))
                    {
                        queue.Add(team);
                    }
                }
                List<SpawnTeam> humanQueue = new List<SpawnTeam>(queue);
                humanQueue.RemoveAll(x => x == SpawnTeam.SCPs);
                for (int i = 0; i < RoleReservation.Reservations.Count; i++)
                {
                    var rr = RoleReservation.Reservations[i];
                    if (rr.RoleType != RoleTypeId.None && !queue.Any(x => rr.RoleType.ToSpawnTeam() == x))
                    {
                        rr.Failed();
                        RoleReservation.Reservations.Remove(rr);
                        i--;
                    }
                }
                SpawnScps(queue.Count(x => x == SpawnTeam.SCPs));
                Log.Info("开始生成人类");
                SpawnHumans(humanQueue);
                AssigningRole();
                Success.ForEach(x => x.Success());
                Fails.ForEach(x => x.Failed());
                RoleReservation.Reservations.ForEach(x => x.Failed());
                ClearAll();
                RoleReservation.Reservations.Clear();
                foreach (Player player in Player.List.Where(x => !x.IsAlive && !x.IsOverwatchEnabled))
                {
                    player.Role.Set(RoleTypeId.Spectator, Exiled.API.Enums.SpawnReason.ForceClass);
                }
                foreach (Player player in Player.List)
                {
                    var data = GameplayData.GameDatas.FirstOrDefault(x => x.Player == player);
                    if (data == null)
                        continue;
                    if (player.IsScp)
                        data.NotScp_Con_Times = 0;
                    else
                        data.NotScp_Con_Times++;
                }
                RgCore.StartRound();
                Log.Info("角色已全部分配完毕，回合开始");
                RoleAssigner._spawned = true;
                RoleAssigner.LateJoinTimer.Restart();
                Scp3114Spawner.OnPlayersSpawned();
                foreach (ReferenceHub referenceHub in ReferenceHub.AllHubs)
                {
                    if (referenceHub.IsAlive())
                    {
                        var player = Player.Get(referenceHub);
                        if (player != null && !player.IsNPC)
                            StartPlayer.Add(player);
                        RoleAssigner.AlreadySpawnedPlayers.Add(referenceHub.authManager.UserId);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            return false;
        }
    }
}
